﻿using Coder.Beer.Robot.Api.ApplicationModel;
using Coder.Beer.Robot.Api.Repository;
using Flurl;
using Flurl.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Mirai.Net.Api.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Coder.Beer.Robot.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CallbackController : ControllerBase
    {
        private readonly BeerDbContext beerDbContext;

        public CallbackController(BeerDbContext beerDbContext)
        {
            this.beerDbContext = beerDbContext;
        }
        [HttpGet("gitee")]
        public async Task<IActionResult> Gitee([FromQuery] string code)
        {
            var response = await $"https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id=52fbf65a494ad533a866c24b8f8612f14c25d3a571868b54ef6af6008ff65285&client_secret=f5fa2e2236adf04ddc7f2a6819bad29e2cbe98d1ee37acfa247acfa7b7965871&redirect_uri=http%3A%2F%2Frobot.coder.beer%2Fapi%2Fcallback%2Fgitee"
                .WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
                .PostJsonAsync(new
                {
                });
            var responseResult = await response.ResponseMessage.Content.ReadAsStringAsync();
            var token = JsonSerializer.Deserialize<GitToken>(responseResult);
            var userInfoString = await $"https://gitee.com/api/v5/user?access_token={token.AccessToken}".GetStringAsync();
            var userInfo = JsonSerializer.Deserialize<GiteeUser>(userInfoString);
            var homeUrl = $"https://gitee.com/{userInfo.Login}";
            var coderUser = await beerDbContext.UserConnecteds.FirstOrDefaultAsync(x => x.GiteeHome == homeUrl);
            coderUser.GiteeToken = token;
            await beerDbContext.SaveChangesAsync();
            return Content("授权完成，请向机器人发送“好了”");
        }


    }
}
